package java_thinking.unit_21._21_10;

/**
 * @Desc:   10-2 容易发生死锁的实例
 * @author: cww
 * @DateTime: 2019/6/20 18:57
 */

public class DynamicOrderDeadlock {
    // Warning: deadlock-prone!
    public static void transferMoney(Account fromAccount,
                                     Account toAccount,
                                     DollarAmount amount)
            throws InsufficientFundsException {
        synchronized (fromAccount) {
            synchronized (toAccount) {
                if (fromAccount.getBalance().compareTo(amount) < 0)
                    throw new InsufficientFundsException();
                else {
                    fromAccount.debit(amount);
                    toAccount.credit(amount);
                }
            }
        }
    }
    static class InsufficientFundsException extends Exception {
    }
}
